package com.coai.rtc.repository

import com.coai.rtc.model.Call
import com.coai.rtc.model.CallParticipant
import com.coai.rtc.model.CallStatus
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
import java.time.LocalDateTime

@Repository
interface CallRepository : JpaRepository<Call, String> {
    
    // 根据会话ID查询通话记录
    fun findByConversationIdOrderByCreatedAtDesc(
        conversationId: String,
        pageable: Pageable
    ): List<Call>
    
    // 查询用户的通话记录
    @Query("""
        SELECT c FROM Call c 
        WHERE c.callerId = :userId 
        OR EXISTS (
            SELECT 1 FROM CallParticipant p 
            WHERE p.callId = c.id AND p.userId = :userId
        )
        ORDER BY c.createdAt DESC
    """)
    fun findUserCalls(userId: String, pageable: Pageable): List<Call>
    
    // 查询活跃通话
    fun findByStatus(status: CallStatus): List<Call>
    
    // 查询时间范围内的通话
    fun findByCreatedAtBetween(
        startTime: LocalDateTime,
        endTime: LocalDateTime,
        pageable: Pageable
    ): List<Call>
}

@Repository
interface CallParticipantRepository : JpaRepository<CallParticipant, String> {
    
    // 查询通话的所有参与者
    fun findByCallId(callId: String): List<CallParticipant>
    
    // 查询用户在通话中的参与记录
    fun findByCallIdAndUserId(callId: String, userId: String): CallParticipant?
    
    // 查询通话中的活跃参与者
    @Query("""
        SELECT p FROM CallParticipant p
        WHERE p.callId = :callId 
        AND p.status = com.coai.rtc.model.ParticipantStatus.JOINED
    """)
    fun findActiveParticipants(callId: String): List<CallParticipant>
    
    // 统计通话参与人数
    fun countByCallId(callId: String): Long
}
